const config = require('../configs/appConfig')
const redis = require('redis');



const redisClient = redis.createClient(config.extConfig.REDIS_CONFIG);

/**
 * 设置key-value
 * @param key 键
 * @param val 值
 * @param timeout 过期时间
 */
function set(key, val, timeout=60*60){
    if(typeof val == 'object'){
        val = JSON.stringify(val);
    }
    redisClient.set(key, val);
    redisClient.expire(key, timeout);
}

function get(key){
    return new Promise((resolve, reject) => {
        redisClient.get(key, (err, val) => {
            if(err){
                reject(err)
                return
            }
            if(val == null){
                resolve(null);
                return;
            }
            try{
                resolve(JSON.parse(val))
            }catch (e) {
                resolve(val);
            }
        })
    })
}

module.exports = {
    set,
    get
}
